$(document).ready(function(){
    $.ajaxSetup({
        cache: false,
        type: 'POST',
        dataType: 'json',
        error: function () {
            alert('Um erro de comunicação com o servidor ocorreu!');
            $('#wait').fadeOut('fast');
        }
    });
    $('textarea.tinymce').tinymce({
        // Location of TinyMCE script
        script_url : '/js/tiny_mce/tiny_mce.js',

        // General options
        theme : "advanced",
        plugins : "pagebreak,style,layer,table,save,advhr,advimage,advlink,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,advlist",

        // Theme options
        theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,styleselect,formatselect,fontselect,fontsizeselect,|,forecolor,backcolor",
        theme_advanced_buttons2 : '',
        theme_advanced_toolbar_location : "top",
        theme_advanced_toolbar_align : "left",
        theme_advanced_statusbar_location : "bottom",
        theme_advanced_resizing : true,

        // Example content CSS (should be your site CSS)
        content_css : "css/content.css",

        // Drop lists for link/image/media/template dialogs
        template_external_list_url : "lists/template_list.js",
        external_link_list_url : "lists/link_list.js",
        external_image_list_url : "lists/image_list.js",
        media_external_list_url : "lists/media_list.js",

        // Replace values for the template plugin
        template_replace_values : {
            username : "Some User",
            staffid : "991234"
        }
    });
    $('#funcionario').autocomplete({
        source: function(request, response) {
            $.ajax({
                url: "/funcionarios/index",
                type: "POST",
                datatype: "json",
                data: {
                    q: request.term
                },
                success: function(data) {
                    //alert(data);
                    response($.map(data, function(item) {
                        return {
                            label: item.nome,
                            value: item.id
                        }
                    }))
                }
            })
        },
        focus: function(event,ui){
            $('#funcionario_id').val(ui.item.label);
            return false;
        },
        open: function(event,ui) {
            $('#funcionario_id').val('');
        },
        select: function(event,ui){
            //alert(ui.item.label);
            $('#funcionario_id').val(ui.item.value);
            $('#funcionario').val(ui.item.label);
            return false;
        },
        minChars : 3
    });

    $('#colaborador').autocomplete({
        source: function(request, response) {
            $.ajax({
                url: "/colaborador/index",
                type: "POST",
                datatype: "json",
                data: {
                    q: request.term
                },
                success: function(data) {
                    response($.map(data.colaboradores, function(item) {
                        return {
                            label: item.nome,
                            value: item.codusu
                        }
                    }))
                }
            })
        },
        focus: function(event,ui){
            $('#colaborador').val(ui.item.label);
            return false;
        },
        open: function(event,ui) {
            $('#colaborador_id').val('');
        },
        select: function(event,ui){
            $('#colaborador_id').val(ui.item.value);
            $('#colaborador').val(ui.item.label);
            if ($('#colaborador_id').val()!=''){
                $.ajax({
                    url: "/contato/index",
                    processData: false,
                    data: 'cliente_id='+$('#colaborador_id').val(),
                    beforeSend: function (){
                        var pos = $('#colaborador').position();
                        var width = $('#colaborador').width();
                        $("#ajax-ldr").css( {
                            "left": (pos.left+width+5) + "px",
                            "top":pos.top + "px"
                        } ).fadeIn('fast');

                    },
                    success: function(msg){
                        $('#contato_id option').remove();
                        $('#contato_id').append("<option value=''>Selecione o Contato...</option>")
                        for (i = 0; i < msg.length; i++) {
                            $('#contato_id').append("<option value='"+msg[i].idcontato+"'>"+msg[i].dsnome+"</option>")
                        }
                        $('#ajax-ldr').fadeOut('fast');
                    }
                });
            }
            return false;
        },
        minLength: 3,
        delay: 300
    });

    $("#dt_visita").datepicker({
        monthNames: ['Janeiro','Fevereiro','Março','Abril','Maio','Junho','Julho','Agosto','Setembro','Outubro','Novembro','Dezembro'],
        dayNamesMin: ['Dom','Seg','Ter','Qua','Qui','Sex','Sab'],
        dateFormat: 'dd/mm/yy'
    });
    $('#submit').button().click(function(){
        $('#modulos :nth-child:hidden').each(function(i,e){
            var aux = $('#usados').val(); 
            $('#usados').val(aux+$(e).val()+',');
        });
        return true;
    });
    $('#btn_insere').button().click(function(){
        //$('#modulos').append('<span class="span-5"><input type="hidden" value="'+$('#sistema_id option:selected').val()+'=>'+$('#modulo_id option:selected').val()+'"/>'+$('#modulo_id option:selected').text()+'</span>');
        $('#modulos').append($('<span>').attr('class','span-5')
            .append($('<span>').attr('class','span-3').text($('#modulo_id option:selected').text()+'('+$('#sistema_id option:selected').val()+')')
                .append($('<input>').attr('type','hidden').val($('#sistema_id option:selected').val()+'=>'+$('#modulo_id option:selected').val())))                                       
            .append($('<span>').attr('class','span-1').append($('<a>').attr('href','#').text('X').click(function(){
                $(this).parent().parent().remove();
            })))
            );
        $('#modulo_id option:selected').remove();
        
    });
    $('#sistema_id').change(function(){
        $.ajax({
            url: "/clientes/modulos",
            processData: false,
            data: 'sistema='+$('#sistema_id').val()+'&cliente='+$('#colaborador_id').val(),
            beforeSend: function (){
                var pos = $('#sistema_id').position();
                var width = $('#sistema_id').width();
                $("#ajax-ldr").css( {
                    "left": (pos.left+width+5) + "px",
                    "top":pos.top + "px"
                } ).fadeIn('fast');

            },
            success: function(msg){
                $('#modulo_id option').remove();
                $('#modulo_id').append("<option value=''>Selecione o Modulo...</option>")
                $.each(msg.contratados,function(k,v){
                    //alert(v);
                    $('#modulo_id').append("<option value='"+v.modulo.codmod+"'>"+v.modulo.descricao+"</option>")
                });
                //for (i = 0; i < msg.length; i++) {
                //$('#modulo_id').append("<option value='"+msg[i].idcontato+"'>"+msg[i].dsnome+"</option>")
                //}
                $('#ajax-ldr').fadeOut('fast');
            }
        });
        $('.removemod').click(function(){
            alert('clicou');
            $(this).parent().parent().remove(); 
            return false;
        });
    });
});
